package com.zenglx.assembly.increasingSequence.starter;

import com.zenglx.assembly.increasingSequence.api.SequenceGeneratorConstant;
import com.zenglx.assembly.increasingSequence.impl.dao.SequenceGeneratorDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import static com.zenglx.assembly.increasingSequence.api.SequenceGeneratorConstant.DEFAULT_OPTIMISTIC_LOCK;


@ConditionalOnProperty(name = SequenceGeneratorConstant.SEQUENCE_GENERATOR_TYPE
        ,  havingValue = SequenceGeneratorConstant.SEQUENCE_GENERATOR_TYPE_PROCEDURE)
@Component
@Slf4j
public class ProcedureInitStartStep implements ApplicationRunner {

    @Value("${com.zenglx.assembly.sequenceGenerator.isAutoCreate:1}")
    private String isAutoCreateProcedure;

    @Value("${com.zenglx.assembly.sequenceGenerator.tableName:optimistic_lock_sequence}")
    private String tableName;


    @Autowired
    private SequenceGeneratorDao sequenceGeneratorDao;

    @Override
    public void run(ApplicationArguments args) {
        log.info("基于存储过程的sequence组件启动,初始化数据开始......");
        if("1".equals(isAutoCreateProcedure)) {
            log.info("基于存储过程的sequence组件自动化创建存储过程");
            //存储过程实现基于表，因此先创建表，初始化一个默认值
            sequenceGeneratorDao.dropTable(tableName);
            sequenceGeneratorDao.createTable(tableName);
            sequenceGeneratorDao.insert(tableName,DEFAULT_OPTIMISTIC_LOCK,1);

            sequenceGeneratorDao.dropProcedure();
            sequenceGeneratorDao.createProcedure(tableName);
        }
        log.info("基于存储过程的sequence组件启动,初始化数据完成");
    }
}
